package api

import (
	"community_end/middleware"
	"community_end/model"
	"community_end/utils/errmsg"
	"fmt"
	"github.com/gin-gonic/gin"
	"net/http"
	"strconv"
	"strings"
)

func GetCommentsByTopicID(ctx *gin.Context) {
	topicID := ctx.Query("topicid")
	//fmt.Println(topicID)

	userComments := []model.UserComments{}
	comments, _ := model.GetCommentsByTopicID(topicID)
	for _, v := range comments {
		convID := strconv.Itoa(v.UserID)
		user, _ := model.SelectUser(convID)
		usercomment := model.UserComments{
			ID:         v.ID,
			Username:   user.Username,
			CreateTime: v.Model.CreatedAt,
			Content:    v.Content,
		}
		userComments = append(userComments, usercomment)
	}

	fmt.Println(userComments)
	ctx.JSON(http.StatusOK, gin.H{
		"code": 200,
		"msg":  errmsg.GetErrMsg(200),
		"data": userComments,
	})
	return
}

func InsertComment(ctx *gin.Context) {
	m := make(map[string]interface{})
	ctx.ShouldBind(&m)
	//fmt.Println(m)

	token := ctx.Request.Header.Get("Authorization")
	userToken, _ := middleware.AuthToken(strings.Split(token, " ")[1])
	user, _ := model.SelectUser(userToken.UserName)

	comment := model.Comment{
		Content: m["content"].(string),
		PostID:  int(m["topic_id"].(float64)),
		UserID:  int(user.ID),
	}

	code := model.InsertComment(comment)
	ctx.JSON(http.StatusOK, gin.H{
		"code": code,
		"msg":  errmsg.GetErrMsg(code),
	})
	return
}
